package ynu.edu.ky_elm_springboot3.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import ynu.edu.ky_elm_springboot3.po.User;
import ynu.edu.ky_elm_springboot3.service.UserService;
import ynu.edu.ky_elm_springboot3.utils.JwtUtil;
import ynu.edu.ky_elm_springboot3.dto.LoginRequest;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Tag(name = "用户相关接口")
@RestController
@RequestMapping("/UserController")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        log.info("Login request received for userId: {}", loginRequest.getUserId());
        
        User user = userService.login(loginRequest.getUserId(), loginRequest.getPassword());
        log.info("Login result: {}", user != null ? "success" : "failed");
        
        if (user != null) {
            String token = jwtUtil.generateToken(user);
            token = "Bearer " + token;
            
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("user", user);
            
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.badRequest().body("用户名或密码错误");
        }
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestParam("userId") String userId,
                                    @RequestParam("password") String password,
                                    @RequestParam("userName") String userName,
                                    @RequestParam("userSex") Integer userSex) {
        log.info("Register request received for userId: {}", userId);
        
        if (userService.getUserById(userId) > 0) {
            log.warn("User already exists: {}", userId);
            return ResponseEntity.badRequest().body("User already exists");
        }

        User user = new User();
        user.setUserId(userId);
        String encodedPassword = passwordEncoder.encode(password);
        log.info("Original password: {}, Encoded password: {}", password, encodedPassword);
        user.setPassword(encodedPassword);
        user.setUserName(userName);
        user.setUserSex(userSex);
        user.setDelTag(1);

        int result = userService.saveUser(user);
        log.info("Registration result: {}", result > 0 ? "success" : "failed");
        
        if (result > 0) {
            return ResponseEntity.ok("User registered successfully");
        }
        
        return ResponseEntity.badRequest().body("Registration failed");
    }

    @Operation(summary = "获取用户信息", security = @SecurityRequirement(name = "Bearer Authentication"))
    @GetMapping("/info")
    public ResponseEntity<?> getUserInfo(@RequestParam String userId) {
        log.info("正在查询用户信息，userId: {}", userId);
        User user = userService.findByUserId(userId);
        if (user == null) {
            log.warn("未找到用户，userId: {}", userId);
            return ResponseEntity.badRequest().body("User not found");
        }
        log.info("查询到用户信息: {}", user);
        return ResponseEntity.ok(user);
    }
} 